package com.atguigu.yygh.user.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YYGHException;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.utils.HttpClientUtils;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.common.utils.RandomUtil;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.prop.WechatProperties;
import com.atguigu.yygh.user.service.UserInfoService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信登录控制层
 */
@Controller
@RequestMapping("/user/wechat")
public class WeChatController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private WechatProperties wechatProperties;

    @GetMapping("/param")
    @ResponseBody //以json格式返回给前端
    public R getWechat() throws Exception {
        //指定编码格式
        String encode = URLEncoder.encode(wechatProperties.getRedirectUrl(), "UTF-8");
        Map<String, Object> resultMap = new HashMap<String, Object>();

        resultMap.put("appid",wechatProperties.getAppId());
        resultMap.put("scope","snsapi_login");
        resultMap.put("redirect_uri",encode);
        resultMap.put("self_redirect",true);
        resultMap.put("state", RandomUtil.getFourBitRandom());

        return R.ok().data(resultMap);
    }

    //用户点击登录后台将登录的结果返回到前端页面
    @GetMapping("/callback")
    public String callback(String code,String state) throws Exception {
        System.out.println(code);
        System.out.println(state);

        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String format = String.format(stringBuilder.toString(), wechatProperties.getAppId(), wechatProperties.getAppSecret(), code);

        JSONObject jsonObject = JSONObject.parseObject(HttpClientUtils.get(format));
        String accessToken = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        UserInfo userInfo = userInfoService.getUserInfoByOpenId(openid);
        if(userInfo == null){
            userInfo=new UserInfo();
            userInfo.setOpenid(openid);
            JSONObject jsonObject1 = JSONObject.parseObject(HttpClientUtils.get("https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid));
            userInfo.setNickName(jsonObject1.getString("nickname"));
            userInfo.setStatus(1);
         userInfoService.save(userInfo);
        }

        if(userInfo.getStatus().intValue() == 0){
            throw new YYGHException(20001,"该用户已被锁定");
        }

        Map<String, String> map=new HashMap<String, String>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }
        map.put("name",name);
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token",token);
        if(StringUtils.isEmpty(userInfo.getPhone())){//如果手机号为空，说明微信号没有绑定过手机号，就携带一个openid
            map.put("openid",openid);
        }else{
            map.put("openid","");
        }
        //跳转到前端页面
        return "redirect:http://localhost:3000/hospital/weixin/callback?token="+map.get("token")+ "&openid="+map.get("openid")+"&name="+URLEncoder.encode(map.get("name"),"utf-8");
    }
//    http://localhost:3000/weixin/callback?token=eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSiox099ANDXYNUtJRSq0oULIyNDO3tLQ0N7Yw01EqLU4t8kxRsjKyhLD9EnNTgXqebd3-csaUp0tWPl-5S6kWAMTEOWpKAAAA.PVvHEGu-vFQ9vEHD7e9vPYqetJimDRjO6wtj9nqQAQD-G0D-sp4JU_-jo_dQfBvR4F1KWQ2Rm3j8gJRC6D1T0w&openid=o3_SC5x5aphOiGL6JK-TkFlbm-rQ&name=海阔天空

}